// pages/confirmorder/confirmorder.js
var app = getApp();
var utils = require('../../utils/util.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        items: [{
                name: '选择自提',
                value: '1'
            },
            {
                name: '送货上门',
                value: '2'
            },
            {
                name: '产地直发',
                value: '3',
                checked: 'true'
            },
        ],
        multiArray: [
            ['今天', '明天', '后天'],
            ['08:00-10:00', '10:00-12:00', '12:00-14:00', '14:00-16:00', '16:00-18:00']
        ],
        multiIndex: [],
        valuetab: 2,
        currentTab: 0,
        currentBut: 0,
        currentBut1: 0,
        isHide: true, //支付弹窗是否显示
        coupon: "",
        typePay: "wx_pay",
        storeId: "", //店铺id  不必须传，只是在自提的时候传输，需在最近的3家店铺获取id
        addressId: "", //地址id  不必须传 需在 我的 我的地址列表中获取id
        couponId: "", //优惠券id  不必须传 需在 、
        deliveryTime: "",
        buttonClicked: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        var that = this;
        that.personalInfo();
        wx.getLocation({
            type: 'wgs84',
            success: function(res) {
                that.setData({
                    latitude: res.latitude,
                    longitude: res.longitude
                })
            }
        })
        //options.type==1  没有选择自提、送货上门、产地直发 单选按钮
        that.setData({
            type: wx.getStorageSync("type"),
            defaultAddress: wx.getStorageSync("defaultAddress"),
            addressId: wx.getStorageSync("defaultAddress").id
        })
    },
    onShow: function() {
        var that = this;
        that.personalInfo();
        if (app.globalData.couponMoney != undefined) {
            that.setData({
                money: app.globalData.couponMoney
            })
        }
        if (app.globalData.couponId != undefined) {
            that.setData({
                couponId: app.globalData.couponId
            })
        }
        var listCar = wx.getStorageSync("listPost");
        var orderCar = [];
        var goodsList = [];
        for (var i in listCar) {
            if (listCar[i].selectStatus == true) {
                orderCar.push(listCar[i])
                goodsList.push({
                    goods_id: listCar[i].id,
                    num: listCar[i].number
                });
            }
        }
        that.setData({
            orderList: orderCar,
            goodsOrder: goodsList,
            type: wx.getStorageSync("type"),
            defaultAddress: wx.getStorageSync("defaultAddress"),
        })
        if (that.data.money != undefined) {
            that.setData({
                coupon: "-" + that.data.money
            })
        } else {
            that.mycouponTap(goodsList);
        }
    },
    //我的个人信息
    personalInfo: function(e) {
        var that = this;
        utils.showLoading();
        utils.http("/api/v1/member/index", {}, function(res) {
            utils.hideLoading();
            that.setData({
                info: res.datas,
            })
            that.all();
            if (that.data.money != undefined) {
                var senyuNme = that.data.totalPrice - that.data.money
                that.setData({
                    oktotalPrice: senyuNme
                })
            } else {
                that.setData({
                    oktotalPrice: that.data.totalPrice
                })
            }
        })

    },
    all: function(listCar) {
        var that = this;
        var totalPrice = 0;
        var price = 0;
        var listCar = that.data.orderList
        for (var i in listCar) {
            price = that.data.info.is_vip == 0 ? listCar[i].price : listCar[i].vip_price;
            totalPrice = totalPrice + (parseInt(listCar[i].number) * parseFloat(price));
        }
        that.setData({
            totalPrice: totalPrice.toFixed(2),
            oktotalPrice: totalPrice.toFixed(2)
        })

    },
    // 获取我的优惠券可使用数据 
    mycouponTap: function(goodslist) {
        var that = this;
        utils.http("/api/v1/order/my_coupon", {
            goods_list: goodslist
        }, function(res) {
            that.setData({
                coupon: "(" + res.datas.use_total + "张优惠卷)"
            })
        })
    },
    //选择自提、送货上门列表
    nearbyStoreList: function(latitude, longitudeq, goodsList) {
        var that = this;
        utils.http("/api/v1/order/nearby_store", {
            latitude: latitude,
            longitude: longitudeq,
            goods_list: goodsList
        }, function(res) {
            that.setData({
                storeList: res.datas,
                storeId: res.datas[0].id
            })
        })
    },
    //订单单选项
    radioChange(e) {
        var that = this;
        this.setData({
            valuetab: e.detail.value
        })
        that.nearbyStoreList(that.data.latitude, that.data.longitude, that.data.goodsOrder);
        if (e.detail.value == 0) {
            that.setData({
                addressId: ""
            })
        }
        if (e.detail.value == 1) {
            that.setData({
                addressId: wx.getStorageSync("defaultAddress").id,
            })
        }
        if (e.detail.value == 2) {
            that.setData({
                addressId: wx.getStorageSync("defaultAddress").id,
            })
        }
    },
    //选择自提
    bindMultiPickerChange(e) {
        console.log(e);
        var that = this;
        var arr = e.detail.value;
        var one = that.data.multiArray[0][arr[0]];
        var two = that.data.multiArray[1][arr[1]];
        this.setData({
            multiIndex: e.detail.value,
            deliveryTime: one + "" + two
        })
    },

    //店铺单项选择 （送货上门）
    bindSvTap: function(e) {
        var id = e.currentTarget.dataset.current;
        this.setData({
            currentTab: id
        })
    },
    //店铺单项选择 （选择自提）
    bindButTap: function(e) {
        var that = this;
        var index = e.currentTarget.dataset.current;
        this.setData({
            currentBut1: index,
            storeId: that.data.storeList[index].id,
        })
    },

    //优惠券
    onCouponTap: function(e) {
        wx.navigateTo({
            url: '../coupon/coupon',
        })
    },
    //关闭支付弹窗
    onColseTap: function(e) {
        this.setData({
            isHide: true
        })
    },
    //打开支付弹窗
    onOrderTap: function(e) {
        this.setData({
            isHide: false
        })
    },
    //支付方式
    paymentTypeTap: function(e) {
        var id = e.currentTarget.dataset.id;
        var currentBut = id;
        this.setData({
            currentBut: currentBut,
            typePay: e.currentTarget.dataset.type,
            buttonClicked: false
        })
    },
    //立即支付
    onOrderSuccessTap: function(e) {
        var that = this;
        if (that.data.buttonClicked==false){

            utils.showLoading();
            that.setData({
                buttonClicked: true
            })
            if (that.data.typePay == "wx_pay") {
                utils.http("/api/v1/order/add_order", {
                    goods_list: that.data.goodsOrder,
                    payment_code: that.data.typePay,
                    get_type: that.data.valuetab,
                    store_id: that.data.storeId,
                    address_id: that.data.addressId,
                    coupon_id: that.data.couponId,
                    delivery_time: that.data.deliveryTime
                }, function (res) {
                    console.log(res);

                    utils.hideLoading();
                    if (res.state == 1) {
                        wx.requestPayment({
                            timeStamp: res.datas.timeStamp,
                            nonceStr: res.datas.nonceStr,
                            package: res.datas.package,
                            signType: res.datas.signType,
                            paySign: res.datas.paySign,
                            success(res) {
                                wx.redirectTo({
                                    url: '../ordersuccess/ordersuccess'
                                })
                            },
                            fail(res) {
                                console.log("skjfdklds")
                                that.setData({
                                    buttonClicked: false
                                })
                             }
                        })
                    }else{
                        utils.message(res.datas);
                    }
                })
            } else if (that.data.typePay == "balance") {
                utils.http("/api/v1/order/add_order", {
                    goods_list: that.data.goodsOrder,
                    payment_code: that.data.typePay,
                    get_type: that.data.valuetab,
                    store_id: that.data.storeId,
                    address_id: that.data.addressId,
                    coupon_id: that.data.couponId
                }, function (res) {
                    utils.hideLoading()
                    if (res.state == 1) {
                        wx.redirectTo({
                            url: '../ordersuccess/ordersuccess'
                        })
                    }else{
                        utils.message(res.datas);
                    }
                })
            }
        }
        

    },
    //跳入我的地址页面
    onMyAddressTap: function(e) {
        app.globalData.typeaddress=0
        wx.redirectTo({
            url: '../personal/myaddress/myaddress?typeaddress=' + app.globalData.typeaddress,
        })
    },
})